﻿//新增排班计划
Ext.namespace('FantastPlatform', 'FantastPlatform.UI');



var detailWind, descriptionWind;

/*****************************************/
//用于存放排班警员的Json

var PoliceManJsonData;

function AddPoliceMan(jsonData) {
    PoliceManJsonData = new Ext.util.JSON.decode(jsonData);
}
/****************************************/

FantastPlatform.UI.PatrolTaskPanel = function (config) {
    Ext.apply(this, config);

    var policeStationComboBox = new Ext.form.ComboBox({
        fieldLabel: '<font color="red">*</font>&nbsp;&nbsp;牵头单位',
        name: 'DutyOrganization',
        hiddenName: 'DutyOrganization',
        store: stationStore,
        displayField: 'Name',
        mode: 'remote',
        valueField: 'Id',
        allowBlank: false,
        editable: false,
        triggerAction: 'all',
        emptyText: '请选择牵头单位...',
        readOnly: true,
        width: 130
    });

    var typeStore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '../Service/PatrolTaskViewService.aspx?Action=GetPatrolTaskType'
        }),
        reader: new Ext.data.JsonReader({
            root: 'topics',
            totalProperty: 'totalCount',
            id: 'Id',
            fields: ['Name', 'Id', 'Code']
        }),
        remoteStore: true

    });
    typeStore.load();
    var policeComboBox = new FantastPlatform.CaseManagement.SearchField({
        fieldLabel: '<font color="red">*</font>&nbsp;&nbsp;责任领导',
        name: 'DutyLeaderName',
        hiddenName: 'DutyLeader',
        valueField: 'Code',
        url: "../Service/DirectiveViewService.aspx?Action=SearchPoliceByStation",
        readOnly: true,
        allowBlank: false,
        blankText: '责任领导不能为空',
        width: 120
    });
    var leaderComboBox = new FantastPlatform.CaseManagement.SearchField({
        fieldLabel: '<font color="red">*</font>牵头单位领导',
        name: 'DefaultLeaderName',
        hiddenName: 'DefaultLeader',
        valueField: 'Code',
        url: "../Service/DirectiveViewService.aspx?Action=SearchPoliceByStation",
        readOnly: true,
        allowBlank: false,
        blankText: '牵头单位领导不能为空',
        width: 120
    });
    var patrolTaskTypeComboBox = new Ext.form.ComboBox({
        fieldLabel: '<font color="red">*</font>&nbsp;&nbsp;指令类型',
        name: 'TaskType',
        hiddenName: 'TaskType',
        store: typeStore,
        displayField: 'Name',
        mode: 'remote',
        valueField: 'Id',
        allowBlank: false,
        editable: false,
        triggerAction: 'all',
        emptyText: '请选择指令类型...',
        readOnly: true,
        width: 130
    });

    var patrolTaskForm = new Ext.form.FormPanel({
        border: false,
        split: true,
        style: 'border:solid 1px',
        labelWidth: 80,
        labelAlign: 'right',
        bodyStyle: 'padding:5px 5px 0',
        height: 220,
        collapsible: true,
        tbar: [{ text: '保存',
            iconCls: 'add',
            id: 'saveSchedule',
            handler: function () {

                if (typeof (ptg) == 'undefined') {
                    submitPanelJson(patrolTaskForm, currtWind, null);
                } else {
                    submitPanelJson(patrolTaskForm, currtWind, ptg);
                }
            }
        }],
        items: [{
            layout: 'column',
            border: false,
            labelSeparator: '：',
            items: [
                 {
                     columnWidth: 0.6,
                     border: false,
                     layout: 'form',
                     items: [new Ext.form.TextField({
                         fieldLabel: '调警指令名称',
                         name: 'Name',
                         allowBlank: false,
                         blankText: '调警指令名称不能为空',
                         width: 350
                     })]
                 },
                 {
                     columnWidth: 0.4,
                     border: false,
                     layout: 'form',
                     items: [patrolTaskTypeComboBox]
                 }
                ,
                 {
                     columnWidth: 0.3,
                     border: false,
                     layout: 'form',
                     items: [policeStationComboBox]
                 }
                    ,
                      {
                          columnWidth: 0.3,
                          border: false,
                          layout: 'form',
                          items: [leaderComboBox]
                      }
                    , {
                        columnWidth: .3,
                        border: false,
                        layout: 'form',
                        items: [policeComboBox]
                    }
                    ,
                     {
                         columnWidth: 0.5,
                         border: false,
                         layout: 'form',
                         items: [new FantastPlatform.UI.DateTimeField({
                             fieldLabel: '<font color="red">*</font>&nbsp;&nbsp;开始时间',
                             allowBlank: false,
                             name: 'BeginTime',
                             timeFormat: 'H:i',
                             blankText: " 开始时间不能为空",
                             dateFormat: 'Y-m-d',
                             width: 200
                         })]
                     }, {
                         columnWidth: 0.5,
                         border: false,
                         layout: 'form',
                         items: [new FantastPlatform.UI.DateTimeField({
                             fieldLabel: '<font color="red">*</font>&nbsp;&nbsp;结束时间',
                             allowBlank: false,
                             name: 'EndTime',
                             timeFormat: 'H:i',
                             blankText: " 结束时间不能为空",
                             dateFormat: 'Y-m-d',
                             width: 200
                         })]
                     }, {
                         columnWidth: 1,
                         border: false,
                         layout: 'form',
                         items: [new Ext.form.TextArea({
                             fieldLabel: '要求',
                             name: 'Require',
                             height: 50,
                             anchor: '95%'
                         })]
                     }, {
                         columnWidth: 1,
                         border: false,
                         layout: 'form',
                         items: [new Ext.form.TextArea({
                             fieldLabel: '备注',
                             name: 'Description',
                             height: 50,
                             anchor: '95%'
                         })]
                     }]
        }]
    });

    this.PatrolTaskForm = patrolTaskForm;
    var MyRecord = new Ext.data.Record.create([
                     { name: 'Id', type: 'int' },
                     { name: 'ExecOrganization', type: 'int' },
                     { name: 'BeginTime', type: 'string' },
                     { name: 'EndTime', type: 'string' }
                ]);
    var editGrid = new FantastPlatform.UI.OrgPatrolTaskGrid({
        height: 300,
        tbar: [{
            text: '添加',
            iconCls: 'new_tab',
            id: 'addDetail',
            handler: cellRecoder
        }, '-', {
            text: '移除',
            iconCls: 'delete',
            id: 'deleteDetail',
            handler: function () {
                var node = checkGridSelected(editGrid);
                if (node) {
                    var id = '';
                    for (var i = 0; i < node.length; i++) {
                        if (node[i].get('Id') == 0) {
                            editGrid.store.remove(node[i]);
                        } else {
                            id += node[i].get('Id') + ",";
                        }
                    }
                    id = id.substring(0, id.length - 1);
                    if (id && id != '' && id != null) {
                        Ext.Msg.confirm('提示', '确认要移除选中的数据吗？', function (btn) {
                            if (btn == 'yes') {
                                Ext.Msg.wait('正在移除数据，请稍候……', '移除数据');
                                //var fIds = getIdFromGrid(node, 'Id');
                                ajaxCalled(null, '../Service/PatrolTaskViewService.aspx?Action=Delete', id, editGrid, null);
                            }

                        })
                    }
                }
            }
        }
        ]
    });
    editGrid.on('cellclick', onCellClick, editGrid);
    function onCellClick(grid, rowIndex, columnIndex, e) {
        var record = grid.getStore().getAt(rowIndex);
        var fieldName = grid.getColumnModel().getDataIndex(columnIndex); // Get field name 
        var data = record.data;
        if (fieldName == 'Url') {
            orgPatrolTaskRecoder = data;
            onEdit(data.Id);
        }
    }
    this.OrgPatrolTaskGrid = editGrid;
    function cellRecoder() {
        var count = editGrid.store.getCount();
        var startTime = "";
        var endTime = "";
        function ChangeTimeToString(DateIn) {
            var Hour = 0;
            var Minute = 0;
            var CurrentDate = "";
            //初始化时间       
             Hour = DateIn.getHours();
            Minute = DateIn.getMinutes();
            if (Hour >= 10) {
                CurrentDate = CurrentDate + " " + Hour;
            }
            else {
                CurrentDate = CurrentDate + " 0" + Hour;
            }
            if (Minute >= 10) {
                CurrentDate = CurrentDate + ":" + Minute;
            }
            else {
                CurrentDate = CurrentDate + ":0" + Minute;
            }
            return CurrentDate;
        }
        if (patrolTaskForm.form.getValues().BeginTime != "") {
            startTime = patrolTaskForm.form.findField("BeginTime").dateValue;
            startTime = ChangeTimeToString(startTime);
        }
        if (patrolTaskForm.form.getValues().BeginTime != "") {
            endTime = patrolTaskForm.form.findField("EndTime").dateValue
            endTime = ChangeTimeToString(endTime);
        }
        var p = new MyRecord({
            Id: 0,
            ExecOrganization: '',
            BeginTime: startTime,
            EndTime: endTime,
            SelfOrgPersonNum: 0,
            SelfOrgCar: 0,
            OtherOrgName: '',
            OtherOrgPersonNum: 0
        })
        editGrid.store.insert(count, p);
        //    var unitCode = policeStationComboBox.getValue();

    }

    function submitPanelJson(form, sender, grid, fn, data) {
        if (form.form.isValid()) {
            var myMask = new Ext.LoadMask(sender.getEl(), {
                msg: "正在保存数据,请稍候...."
            });
            var dataStr = Ext.util.JSON.encode(form.form.getValues());
            if (data) {
                dataStr = dataStr.substring(0, dataStr.length - 1) + "," + data + "}";
            }
            if (editGrid) {
                var records = editGrid.store.getRange();
                var dataStr1 = '{"OrgPatrolTaskList":[';
                for (var i = 0; i < records.length; i++) {
                    dataStr1 += '{"Id":"' + records[i].get("Id") + '","BeginTimeStr":"' + records[i].get("BeginTime") + '", "EndTimeStr":"' + records[i].get("EndTime") + '","ExecOrganization":"' + records[i].get("ExecOrganization") + '","Points":' + records[i].get("Points") + '},';

                }
                if (dataStr1 && records.length != 0) {
                    dataStr1 = dataStr1.substring(0, dataStr1.length - 1);
                }
                dataStr1 += "]}";
            }
            var url = '../Service/PatrolTaskViewService.aspx?Action=Add';
            myMask.show();
            Ext.Ajax.request({
                method: 'post',
                url: url,
                params: { data: dataStr, data1: dataStr1, StartTime: form.form.getValues().ScheduleStartTime, EndTime: form.form.getValues().ScheduleEndTime },
                success: onSuccess,
                failure: onFailure
            });

            function onFailure(request, options) {
                myMask.hide();
                showErrorMessage('操作失败', request.responseText, '');
            }

            function onSuccess(request, options) {
                // 服务器返回json形式的结果
                myMask.hide();
                var reText = request.responseText;
                var reTextObj = Ext.util.JSON.decode(reText);
                if (eval(reTextObj.success)) {
                    showMessage('操作成功', '保存排班计划成功');
                    if (grid)
                        updata(grid);
                    if (fn)
                        fn.call(this, reText);
                    if (sender)
                        sender.close();
                } else {
                    showErrorMessage('操作失败', reTextObj.message, '');
                }
            }

        }
    };

    this.items = [
    {
        columnWidth: 1,
        border: false,
        items: [patrolTaskForm]
    },
    {
        columnWidth: 1,
        border: false,
        items: [editGrid]
    }
    ];
    FantastPlatform.UI.PatrolTaskPanel.superclass.constructor.call(this, {
        layout: 'column',
        border: false
    });
};
Ext.extend(FantastPlatform.UI.PatrolTaskPanel, Ext.Panel, {
    onRender: function (ct, position) {
        FantastPlatform.UI.PatrolTaskPanel.superclass.onRender.call(this, ct, position);
        if (this.Id && this.Id != 0) {
            this.PatrolTaskForm.add(new Ext.form.Hidden({ name: 'Id', value: this.Id }));
            var grid = this.OrgPatrolTaskGrid;
            var gridId = this.Id;
            var formUrl = this.FormUrl;
            var gridUrl = this.GridUrl;
            this.PatrolTaskForm.load({
                url: formUrl,
                params: { id: this.Id },
                waitMsg: '正在读取数据...',
                waitTitle: '请稍后',
                success: function (form, action) {
                    grid.store.proxy.conn = {
                        url: gridUrl
                    };
                    grid.store.baseParams = { id: gridId };
                    grid.store.load({ params: { start: 0, limit: grid.paperBar.defaultNum, dir: '', sort: ''} });

                },
                failure: function (form, action) {
                    if (action.failureType != 'client') {
                        showErrorMessage('操作失败', action.result.message, '');
                    }
                }
            })

        }
    }

});  